﻿using System;
using System.Net;
using Tycho.Compiler;
using Tycho.Language;
using Tycho.Runtime;

namespace Tycho.Modules {
    public class HttpModuleLoader : IModuleLoader {
        private string BaseUrl;
        private readonly IModuleCompiler ModuleCompiler;

        public HttpModuleLoader (string baseUrl, IModuleCompiler moduleCompiler) {
            if (!baseUrl.EndsWith ("/")) {
                baseUrl += "/";
            }
            BaseUrl = baseUrl;
            ModuleCompiler = moduleCompiler;
        }

        public AnyObject LoadModule (Namespace ns, string [] modulePath, IModuleScopeLoader moduleLoader) {
            string url = BaseUrl + String.Join ("/", ns.Path) + ".tycho";

            try {
                string source = new WebClient ().DownloadString (url);

                return ModuleCompiler.CompileModule (source, url, ns, moduleLoader);
            } catch (WebException) {
                return null;
            }
        }
    }
}
